package com.sbj.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.zhxu.bs.BeanSearcher;
import cn.zhxu.bs.operator.Contain;
import cn.zhxu.bs.operator.Equal;
import cn.zhxu.bs.util.MapBuilder;
import cn.zhxu.bs.util.MapUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sbj.config.BuyOrderConfig;
import com.sbj.dto.req.BuyReq;
import com.sbj.dto.req.MemberStoreReq;
import com.sbj.dto.req.TransferGoodReq;
import com.sbj.dto.res.MemberStoreRes;
import com.sbj.dto.res.TransferRationRes;
import com.sbj.dto.utils.JWTUtils;
import com.sbj.dto.utils.Search;
import com.sbj.entity.*;
import com.sbj.mapper.MemberStoreMapper;
import com.sbj.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zmh.framework.constants.Constants;
import com.zmh.framework.exception.ResultException;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author summer
 * @since 2024/08/10 10:02:41
 */
@Service
@Transactional(rollbackFor = Exception.class)
@AllArgsConstructor
public class MemberStoreServiceImpl extends ServiceImpl<MemberStoreMapper, MemberStore> implements IMemberStoreService {

    private final BeanSearcher beanSearcher;

    @Override
    public  Page<MemberStoreRes> lists(MemberStoreReq memberStoreReq) {
        Map<String, Object> build = MapUtils.builder().page(memberStoreReq.getPageNum() - 1, memberStoreReq.getPageSize())
                .field(MemberStoreRes::getBuyerName, memberStoreReq.getBuyerName()).op(Contain.class)
                .field(MemberStoreRes::getBuyerPhone, memberStoreReq.getBuyerPhone()).op(Contain.class)
                .field(MemberStoreRes::getSellerName, memberStoreReq.getSellerName()).op(Contain.class)
                .field(MemberStoreRes::getSellerPhone, memberStoreReq.getSellerPhone()).op(Contain.class)
                .field(MemberStoreRes::getType,memberStoreReq.getType()).op(Equal.class).build();
        return Search.searchDataList(memberStoreReq.getPageNum(), memberStoreReq.getPageSize(),beanSearcher.search(MemberStoreRes.class,build));
    }

    @Override
    public Page<MemberStoreRes> buyerOrderLists(MemberStoreReq req) {
        if(req.getType().equals(Constants.ONE) && ObjectUtil.isNotEmpty(req.getOrderState()) && req.getOrderState().equals(Constants.ZERO)){

            req.setOrderState(3);
        }
        MapBuilder mapBuilder =MapUtils.builder()
                .page(req.getPageNum() - 1, req.getPageSize())
                .field(MemberStoreRes::getType,req.getType())
                .field(MemberStoreRes::getOrderState, req.getOrderState());
        if(req.getType().equals(Constants.ZERO)){
            mapBuilder.field(MemberStoreRes::getBuyerId, StpUtil.getLoginIdAsInt());
         }else if(req.getType().equals(Constants.ONE)){
            mapBuilder.field(MemberStoreRes::getSellerId, StpUtil.getLoginIdAsInt());
        }
         return Search.searchDataList(req.getPageNum(), req.getPageSize(),beanSearcher.search(MemberStoreRes.class, mapBuilder.build()));
    }





    @Override
    public void buyOrderPay(BuyReq req) {
        MemberStore memberStore = this.getById(req.getId());
        if(ObjectUtil.isEmpty(memberStore)){
            throw new ResultException("支付订单不存在");
        }
        memberStore.setCompleteTime(LocalDateTime.now());
        memberStore.setPay(req.getPay());
        memberStore.setOrderState(Constants.ONE);
        memberStore.setPayMethod(req.getPayMethod());
        memberStore.setAddressId(req.getAddressId());
        BuyGoods buyGoods = goodsService.getById(memberStore.getBuyId());
        if(ObjectUtil.isNotEmpty(buyGoods.getBuyOrderId())){
            MemberStore store = this.getById(buyGoods.getBuyOrderId());
            store.setOrderState(Constants.ONE);
            store.setCompleteTime(LocalDateTime.now());
            this.updateById(store);
        }

        this.updateById(memberStore);
        //保存推广金额
        extensionService.saveExtension(memberStore.getGoodsPrice(),3);
       //奖金金额
        extensionService.saveExtension(memberStore.getGoodsPrice(),Constants.TWO);

    }

    private final ExtensionService extensionService;

    private final TransferService transferService;

    private final IMemberService memberService;

    @Override
    public TransferRationRes getTransferRatio(Integer id) {
        TransferRationRes transferRationRes=new TransferRationRes();
        MemberStore memberStore = this.getById(id);
        if(ObjectUtil.isEmpty(memberStore)){
            throw new ResultException("订单不存在");
        }
        Transfer transfer=transferService.findOne();
        BigDecimal bigDecimal = JWTUtils.orderAmount(memberStore.getGoodsPrice(), transfer.getRatio());
        transferRationRes.setId(id);
        transferRationRes.setTransferAmount(bigDecimal);
        transferRationRes.setOriginal(memberStore.getGoodsPrice());
        Member member = memberService.getById(StpUtil.getLoginIdAsInt());
        transferRationRes.setBalance(member.getBalance());
        return transferRationRes;
    }


    private final DivisionService divisionService;

    private final IBuyGoodsService goodsService;

    private final BuyOrderConfig buyOrderConfig;


    @Override
    public MemberStoreRes memberStoreInfo(Integer id) {
        MapBuilder field = MapUtils.builder().field(MemberStoreRes::getId, id);
        return beanSearcher.searchFirst(MemberStoreRes.class, field.build());
    }

    @Override
    public void transferGoods(TransferGoodReq req) {
        TransferRationRes transferRatio = getTransferRatio(req.getId());
        MapBuilder field = MapUtils.builder().field(MemberStoreRes::getId, req.getId());
        MemberStoreRes memberStoreRes = beanSearcher.searchFirst(MemberStoreRes.class, field.build());
        Division division=divisionService.findOne();
        if(NumberUtil.isGreaterOrEqual(transferRatio.getTransferAmount(),division.getAmount())){
            BigDecimal tradeAmount = NumberUtil.div(transferRatio.getTransferAmount(), division.getQuantity());
            List<BuyGoods> list= ListUtil.list(true);
            for (int i=0;i<division.getQuantity();i++){
                insertBuyGoods(tradeAmount,memberStoreRes.getGoodsName());
            }
        }else{
            insertBuyGoods(transferRatio.getTransferAmount(),memberStoreRes.getGoodsName());
        }
        MemberStore memberStore = this.getById(req.getId());
        memberStore.setTransfer(Constants.ONE);
        this.updateById(memberStore);

    }

    private void insertBuyGoods( BigDecimal tradeAmount,String goodsName){
        MemberStore memberStore = buyOrderConfig.memberStore( tradeAmount);
        this.save(memberStore);
        BuyGoods buyGoods = new BuyGoods();
        buyGoods.setMemberId(StpUtil.getLoginIdAsInt());
        buyGoods.setGoodsPrice(tradeAmount);
        buyGoods.setGrounding(1);
        buyGoods.setGoodsNum(Constants.ONE);
        buyGoods.setGoodsName(goodsName);
        buyGoods.setBuyOrderId(memberStore.getId());
        goodsService.save(buyGoods);
        memberStore.setBuyId(buyGoods.getId());
        this.updateById(memberStore);
    }

}
